package com.taptech.doufu.ui.activity.story

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.taptech.doufu.R
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.event.EventBusMyTag
import com.taptech.doufu.event.EventBusRefreshMyStory
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.ui.activity.AddTagTosActivity
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.taptech.doufu.ui.view.WaitDialog
import com.taptech.doufu.util.GsonUtil
import com.taptech.doufu.util.StringUtil
import com.taptech.doufu.weex.http.TFHttpUtil
import com.taptech.doufu.weex.http.TFHttpUtil.Param
import kotlinx.android.synthetic.main.activity_story_code.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class StoryCodeActivity:DiaobaoBaseActivity() {

    var tagsList = mutableListOf<String>()
    var id = 0
    var hasPublish = false
    var oldTitle = ""
    var oldContent = ""
    var oldTagsList = mutableListOf<String>()
    lateinit var waitDialog: WaitDialog

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMyTagChange(event: EventBusMyTag) {
        if (event != null && !TextUtils.isEmpty(event.tag) && event.tag == EventBusMyTag.tag && event.list != null) {
            tagsList = event.list
            updateTags()
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_story_code)
        EventBus.getDefault().register(this)
        id = intent.getIntExtra(Constant.ID,0)
        waitDialog = WaitDialog(this,R.style.updateDialog)
        ivBack.setOnClickListener {
            goBack()
        }

        tvPublic.setOnClickListener {
            uploadData(1)
        }

        getData()
        etContent.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                tvCount.text = "${s?.toString()?.replace("\\s+".toRegex(), "")?.length}"
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
        layTag.setOnClickListener {
            jumpToTag()
        }
    }

    fun updateTags() {
        if (tagsList.size > 0) {
            layAddTag.visibility = View.GONE
            laySelectTag.visibility = View.VISIBLE
            tvTag1.visibility = View.VISIBLE
            tvTag1.text = tagsList[0]
            tvTag2.visibility = View.GONE
            tvTag3.visibility = View.GONE
            if (tagsList.size > 1){
                tvTag2.visibility = View.VISIBLE
                tvTag2.text = tagsList[1]
            }
            if (tagsList.size > 2){
                tvTag3.visibility = View.VISIBLE
                tvTag3.text = tagsList[2]
            }
        }else{
            layAddTag.visibility = View.VISIBLE
            laySelectTag.visibility = View.GONE
        }
    }



    fun uploadData(publish:Int) {

        if (publish>0 && etTitle.text.toString().isNullOrEmpty()) {
            Toast.makeText(thisActivity,"请填写标题",Toast.LENGTH_LONG).show()
            return
        }
        waitDialog.show()
        var url = "http://api.doufu.la/post/saveTopic"
        val params = mutableListOf<Param>()
        params.add(TFHttpUtil().Param("publish",publish))
        params.add(TFHttpUtil().Param("single_page",1))
        if (id > 0) {
            params.add(TFHttpUtil().Param("id",id))
        }
        params.add(TFHttpUtil().Param("description",etContent.text.toString()))
        params.add(TFHttpUtil().Param("title",etTitle.text.toString()))
        tagsList.forEach {
            params.add(TFHttpUtil().Param("tags[]","${it}|0"))
        }
        TFHttpUtil.requestPostRepeatParam(url, params){json, error ->
            try {
                val data = json.getJSONObject("data")
                if (data != null && data.getIntValue("id") > 0) {
                    if (publish > 0) {
                        Toast.makeText(thisActivity,"发布成功",Toast.LENGTH_LONG).show()
                    }else{
                        Toast.makeText(thisActivity,"保存成功",Toast.LENGTH_LONG).show()
                    }
                    val event = EventBusRefreshMyStory()
                    event.tag = EventBusRefreshMyStory.tag
                    EventBus.getDefault().post(event)
                    finish()
                }else{
                    val msg = json.getString("user_msg")
                    if (msg.isNullOrEmpty()) {
                        if (publish > 0) {
                            Toast.makeText(thisActivity,"发布失败",Toast.LENGTH_LONG).show()
                        }else{
                            Toast.makeText(thisActivity,"保存失败",Toast.LENGTH_LONG).show()
                        }
                    }else{
                        Toast.makeText(thisActivity,msg,Toast.LENGTH_LONG).show()
                    }

                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            waitDialog.dismiss()
        }
    }


    fun getData() {
        if (id == 0) return
        waitDialog.show()
        val url = "http://api.doufu.la/topic/novel"
        val params = mutableMapOf<String,Any>()
        params["topic_id"] = id
        params["write"] = 1
        TFHttpUtil.requestGet(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                val topic = data.getJSONObject("topic")
                val detail = GsonUtil.parseJsonWithGson(topic.toJSONString(), NovelDetailBean::class.java)
                oldContent = detail.description
                oldTitle = detail.title
                if (oldContent.isNotEmpty()) {
                    etContent.setText(oldContent)
                }
                if (oldTitle.isNotEmpty()) {
                    etTitle.setText(oldTitle)
                }
                if (detail.status > 0) {
                    hasPublish = true
                }
                detail.tags.forEach {
                    tagsList.add(it.name)
                    oldTagsList.add(it.name)
                }
                updateTags()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            waitDialog.dismiss()
        }
    }


    private fun jumpToTag() {
        //跳转到自定义页面
        val intent = Intent(this, AddTagTosActivity::class.java)
        intent.putExtra("existTagsList", ArrayList(tagsList))
        intent.putExtra( "SIZE", 3)
        intent.putExtra("TYPE_FROM", Constant.OBJECT_TYPE_NOVEL)
        intent.putExtra("SINGLE_PAGE",1)
        startActivity(intent)
    }


    fun toastDraftDialog() {
        val dialog = BottomSheetDialog(this)
        dialog.setContentView(R.layout.dialog_bottom_sheet_draft)
        val tvGiveUp = dialog.findViewById<TextView>(R.id.tvGiveUp)
        tvGiveUp?.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        val tvSave = dialog.findViewById<TextView>(R.id.tvSave)
        tvSave?.setOnClickListener {
            uploadData(0)
            dialog.dismiss()
        }
        val tvCancel = dialog.findViewById<TextView>(R.id.tvCancel)
        tvCancel?.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }

    fun toastPublishDialog() {
        val dialog = BottomSheetDialog(this)
        dialog.setContentView(R.layout.dialog_bottom_sheet_public)
        val tvGiveUp = dialog.findViewById<TextView>(R.id.tvGiveUp)
        tvGiveUp?.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        val tvCancel = dialog.findViewById<TextView>(R.id.tvCancel)
        tvCancel?.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }


    fun goBack() {
        if (isDataChange()) {
            if (hasPublish) {
                toastPublishDialog()
            }else{
                toastDraftDialog()
            }
        }else{
            finish()
        }
    }

    fun isDataChange() :Boolean{
        if (oldTitle != etTitle.text.toString()) {
            return true
        }
        if (oldContent != etContent.text.toString()) {
            return true
        }
        if (oldTagsList.size != tagsList.size) {
            return true
        }
        oldTagsList.forEachIndexed { index, s ->
            if (s != tagsList[index]) {
                return true
            }
        }
        return false
    }



    override fun onBackPressed() {
        goBack()
    }

    companion object{
        fun startActivity(context: Context) {
            val intent = Intent()
            intent.setClass(context,StoryCodeActivity::class.java)
            context.startActivity(intent)
        }

        fun startActivity(context: Context,id:Int) {
            val intent = Intent()
            intent.setClass(context,StoryCodeActivity::class.java)
            intent.putExtra(Constant.ID,id)
            context.startActivity(intent)
        }
    }
}